package com.cs.micro.mail.support;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.IOException;
import java.util.Map;

/**
 * freemarker渲染工具
 *
 * @author wangjiahao
 * @version 1.0
 * @className FtlUtils
 * @since 2019-03-28 14:39
 */
public class FtlUtils {

    private static Configuration cfg = null;

    private static Template getTemplate(String file) throws IOException {
        return cfg.getTemplate(file);
    }

    static void init() {
        cfg = new Configuration(Configuration.VERSION_2_3_0);
        cfg.setDefaultEncoding("utf-8");
        cfg.setWhitespaceStripping(false);
        cfg.setClassForTemplateLoading(FtlUtils.class, "/templates/");
    }

    /**
     * 渲染模板，返回字符串
     */
    public static String render(String file,Map<String,Object> model) throws IOException, TemplateException {
        init();
        return FreeMarkerTemplateUtils.processTemplateIntoString(getTemplate(file), model);
    }
}
